package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.SysAreaBo;
import com.ruoyi.system.domain.vo.SysAreaVo;
import com.ruoyi.system.domain.SysArea;
import com.ruoyi.system.mapper.SysAreaMapper;
import com.ruoyi.system.service.ISysAreaService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 区域架构Service业务层处理
 *
 * @author xhw
 * @date 2023-07-17
 */
@RequiredArgsConstructor
@Service
public class SysAreaServiceImpl implements ISysAreaService {

    private final SysAreaMapper baseMapper;

    /**
     * 查询区域架构
     */
    @Override
    public SysAreaVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }


    /**
     * 查询区域架构列表
     */
    @Override
    public List<SysAreaVo> queryList(SysAreaBo bo) {
        LambdaQueryWrapper<SysArea> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysArea> buildQueryWrapper(SysAreaBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysArea> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getParentId() != null, SysArea::getParentId, bo.getParentId());
        lqw.like(StringUtils.isNotBlank(bo.getAreaName()), SysArea::getAreaName, bo.getAreaName());
        lqw.eq(StringUtils.isNotBlank(bo.getAreaCode()), SysArea::getAreaCode, bo.getAreaCode());
        lqw.eq(StringUtils.isNotBlank(bo.getAreaLeave()), SysArea::getAreaLeave, bo.getAreaLeave());
        return lqw;
    }

    /**
     * 新增区域架构
     */
    @Override
    public Boolean insertByBo(SysAreaBo bo) {
        SysArea add = BeanUtil.toBean(bo, SysArea.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改区域架构
     */
    @Override
    public Boolean updateByBo(SysAreaBo bo) {
        SysArea update = BeanUtil.toBean(bo, SysArea.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysArea entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除区域架构
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
